<script setup>
import SearchTable from '@/components/SearchTable.vue'
import { reactive, ref, nextTick } from 'vue';
import Upload from '@/components/Upload.vue'
import categoryApi from '@/api/categoryApi'
import { Message } from '@arco-design/web-vue'
import { VueDraggable } from 'vue-draggable-plus'
import constants from "@/utils/constants";


const searchModel = reactive({})
const visible = ref(false)
const submitData = ref({})
const submitForm = ref()
const searchForm = ref()
const searchListTable = ref()
const selectRow = ref({})
const goodSearchModel = ref({
    isOnSale: true
})
const visibleChooseGood = ref(false)
const selectedGoodKeys = ref([]);
const goodList = ref([])
const goodTable = ref()

const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
    fixed: true
})

const columns = [
    { title: '分类名称', dataIndex: 'name', width: 150 },
    { title: '分类排序', dataIndex: 'sortId', width: 80 },
    { title: '默认图标', slotName: 'iconPath', width: 50 },
    { title: '选中图标', slotName: 'selectedIconPath', width: 50 },
    { title: '操作', slotName: 'action', width: 120 },
]

const goodColumns = [
    {
        title: "商品编码",
        dataIndex: "goodsId",
        width: 100,
    },
    {
        title: "商品图片",
        slotName: "goodsThumb",
        width: 120,
    },
    {
        title: "商品名称",
        dataIndex: "goodsName"
    },
    {
        title: "是否上架",
        slotName: "isOnSale",
        width: 100,
    },
    {
        title: "排序",
        dataIndex: "sortOrder",
        width: 60,
    }
];
const addDialog = () => {
    visible.value = true
    submitForm.value.resetFields()
    submitData.value = {}
}

const editRecord = (record) => {
    visible.value = true
    nextTick(() => {
        submitForm.value.resetFields()
        submitData.value = Object.assign({}, record)
    })
}

const handleSubmitSuccess = (values) => {
    categoryApi.save(values).then((res) => {
        visible.value = false;
        Message.success("保存成功");
        search();
    });
}

const activeRowClass = (record) => {
    return record.id === selectRow.value.id ? 'activeRowLight' : ''
}

const selectCategory = (record) => {
    selectRow.value = record;
    queryCategoryGoods(record.id);
}

const loadingGood = ref(false)
const queryCategoryGoods = (id) => {
    loadingGood.value = true
    categoryApi.queryGoods({
        id: id
    }).then((res) => {
        goodList.value = res
        loadingGood.value = false
    }).catch(() => {
        loadingGood.value = false
    });
}

const saveGoods = () => {
    let goodList = []
    for (let i = 0; i < selectedGoodKeys.value.length; i++) {
        goodList.push({
            goodsId: selectedGoodKeys.value[i],
            sortOrder: i
        })
    }
    categoryApi.saveGoods({
        id: selectRow.value.id,
        goodList: goodList
    }).then((res) => {
        Message.success("保存成功");
        visibleChooseGood.value = false
        queryCategoryGoods(selectRow.value.id);
    }).catch(() => {
    });
}

const updateGoodSort = () => {
    let goods = [];
    for (let i = 0; i < goodList.value.length; i++) {
        let goodItem = goodList.value[i];
        goods.push({
            goodsId: goodItem.goodId,
            sortOrder: i
        })
    }
    categoryApi.saveGoods({
        id: selectRow.value.id,
        goodList: goods
    }).then((res) => {
        Message.success("保存成功");
        visibleChooseGood.value = false
        queryCategoryGoods(selectRow.value.id);
    }).catch(() => {
    });
}

const deleteCategoryGood = (id) => {
    categoryApi.deleteCategoryRelGood({
        id: id,
    }).then((res) => {
        queryCategoryGoods(selectRow.value.id);
    }).catch(() => {
    });
}

const deleteRecord = (record) => {
    categoryApi.delete({
        id: record.id,
    }).then((res) => {
        search()
    }).catch(() => {
    });
}

const openChooseGood = () => {
    visibleChooseGood.value = true
    selectedGoodKeys.value = []
    goodList.value.forEach(item => {
        selectedGoodKeys.value.push(item.goodId)
    })
}

const search = () => {
    searchListTable.value.load()
}
const searchGood = () => {
    goodTable.value.load()
}
</script>
<template>
    <div class="main-con flex flex1">
        <a-row :gutter="10" class="vh">
            <a-col :span="9">
                <search-table ref="searchListTable" :row-class="activeRowClass" @row-click="selectCategory"
                    :columns="columns" url="/goodCategory/queryPage" :params="searchModel">
                    <template #toolbar>
                        <a-space>
                            <a-button type="primary" @click="addDialog">新增分类</a-button>
                        </a-space>
                    </template>
                    <template #iconPath="{ record }">
                        <a-avatar v-if="record.iconPath" :size="24">
                            <img alt="avatar" :src="constants.imgDomain + record.iconPath"
                                style="width:24px;height: 24px;" />
                        </a-avatar>
                        <span v-else style="color: #999;">—</span>
                    </template>
                    <template #selectedIconPath="{ record }">
                        <a-avatar v-if="record.selectedIconPath" :size="24">
                            <img alt="avatar" :src="constants.imgDomain + record.selectedIconPath"
                                style="width:24px;height: 24px;" />
                        </a-avatar>
                        <span v-else style="color: #999;">—</span>
                    </template>
                    <template #action="{ record }">
                        <a-space>
                            <a-button @click="editRecord(record)" type="text">编辑</a-button>
                            <a-popconfirm content="确定要删除该分类吗?" @ok="deleteRecord(record)">
                                <a-button type="text">删除</a-button>
                            </a-popconfirm>
                        </a-space>
                    </template>
                </search-table>
            </a-col>
            <a-col :span="15">
                <a-card title="分类商品排墙">
                    <a-spin :loading="loadingGood" fill style="width: 100%;">
                        <div class="toolbar">
                            <a-space>
                                <a-button :disabled="!selectRow.id" @click="openChooseGood">选择商品</a-button>

                                <a-button :disabled="!selectRow.id" @click="updateGoodSort">
                                    <template #icon>
                                        <icon-sort />
                                    </template>
                                    保存商品
                                </a-button>

                                <span v-if="selectRow.id" style="color:red">商品可拖动排序,此排序也是小程序商品展示排序</span>
                            </a-space>
                        </div>
                        <a-empty v-if="!goodList || goodList.length == 0" />
                        <VueDraggable ref="el" v-model="goodList">
                            <div v-for="item in goodList" :key="item.good.goodsId" class="choose-good-item">
                                <div class="good-img">
                                    <a-image :src="constants.imgDomain + item.good.goodsThumb + '?imageslim/zlevel/7'"
                                        width="100"></a-image>
                                    <div class="delete-icon">
                                        <a-popconfirm content="确定要从该商品分类中删除该商品吗?" @ok="deleteCategoryGood(item.id)">
                                            <icon-minus-circle size="24" />
                                        </a-popconfirm>
                                    </div>
                                </div>
                                <div class="good-name">
                                    {{ item.good.goodsName }}
                                </div>
                            </div>
                        </VueDraggable>
                    </a-spin>
                </a-card>
            </a-col>
        </a-row>
    </div>
    <a-modal v-model:visible="visible" title="新增分类" :footer="null">
        <a-form ref="submitForm" :model="submitData" auto-label-width @submit-success="handleSubmitSuccess">
            <a-form-item label="分类名称" field="name" :rules="[{ required: true, message: '请输入分类名称' }]">
                <a-input v-model="submitData.name" placeholder="分类名称"></a-input>
            </a-form-item>
            <a-form-item label="分类排序" field="sortId" :rules="[{ required: true, message: '请输入分类排序' }]">
                <a-input-number v-model="submitData.sortId" placeholder="分类排序"></a-input-number>
            </a-form-item>
            <a-form-item label="默认图标" field="iconPath">
                <Upload tip="上传图标" :height="80" :width="80" v-model="submitData.iconPath"></Upload>
            </a-form-item>
            <a-form-item label="选中图标" field="selectedIconPath">
                <Upload tip="选中图标" :height="80" :width="80" v-model="submitData.selectedIconPath"></Upload>
            </a-form-item>
            <div class="flex flex-center btn-area">
                <a-space>
                    <a-button html-type="submit" type="primary">保存</a-button>
                    <a-button @click="() => {
                        visible = false;
                    }
                        ">取消</a-button>
                </a-space>
            </div>
        </a-form>
    </a-modal>
    <a-modal v-model:visible="visibleChooseGood" title="商品列表" width="70%" :footer="null">
        <search-table ref="goodTable" :columns="goodColumns" v-model:selectedKeys="selectedGoodKeys"
            :row-selection="rowSelection" row-key="goodsId" :params="goodSearchModel" url="/good/queryPage">
            <template #toolbar>
                <a-form ref="searchForm" :model="goodSearchModel">
                    <a-row :gutter="16">
                        <a-col :span="8">
                            <a-form-item field="goodsName" label="商品名称">
                                <a-input v-model="goodSearchModel.goodsName" placeholder="请输入商品名称" />
                            </a-form-item>
                        </a-col>
                        <a-col :span="8">
                            <a-form-item field="isOnSale" label="是否上架">
                                <a-select v-model="goodSearchModel.isOnSale" allow-clear placeholder="请选择"
                                    :options="constants.onSaleStatues">
                                </a-select>
                            </a-form-item>
                        </a-col>
                        <a-col :span="8">
                            <a-form-item>
                                <a-space>
                                    <a-button type="primary" @click="searchGood">查询</a-button>
                                    <a-button @click="searchForm.resetFields()">重置</a-button>
                                </a-space>
                            </a-form-item>
                        </a-col>
                    </a-row>
                </a-form>
            </template>
            <template #goodsThumb="{ record }">
                <a-image :src="constants.imgDomain + record.goodsThumb + '?imageslim/zlevel/7'" width="50"></a-image>
            </template>
            <template #isOnSale="{ record }">
                <a-tag :color="record.isOnSale ? '#00AAFF' : ''">{{ record.isOnSale ? '已上架' : '未上架' }}</a-tag>
            </template>
        </search-table>
        <div class="flex flex-center btn-area">
            <a-space>
                <a-button type="primary" :disabled="!selectedGoodKeys || selectedGoodKeys.length == 0"
                    @click="saveGoods">保存</a-button>
                <a-button @click="visibleChooseGood = false">取消</a-button>
            </a-space>
        </div>
    </a-modal>
</template>
<style scoped lang="less">
.choose-good-item {
    // height: 100px;
    width: calc(100% / 5);
    float: left;
    cursor: pointer;
    margin-top: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;

    .good-img {
        position: relative;

        .delete-icon {
            position: absolute;
            top: -10px;
            right: -20px;
            z-index: 9;
        }
    }

    .good-name {
        position: relative;
        margin-top: 10px;
        font-weight: 600;

    }

}
</style>